import { container } from "tsyringe";
import { httpGet, httpGetSync2 } from "../../autox/http";
import { Task } from "../../autox/task";
import { getDeviceUuid } from "../../tokens";
import { $, updateFloat } from "../../utils";
import { IScheduleTask } from "../node";
import { RedPacket } from "./RedPacket";
import { OpenLiveRoomAction, ToLiveRoomAction, ToShouYeAction, WaitRedOpenAction } from "./action";
import { Thread } from "threads";
declare const runtime: any;

export class KwaiQiangBaoSheduleTask implements IScheduleTask {
    time: number = 1000 * 60 * 60;
    sleep: number = 1000 * 50 * 10;
    title: string = `【快手抢包】`;
    isRuning: boolean = false;
    task: Task;
    constructor() {
        this.task = container.resolve(Task)
    }
    check(): boolean {
        // if (this.redPackets.length === 0) {
        //     return true;
        // }
        // if (this.redPackets.find(red => [6, 2, 0].includes(red.type))) {
        //     return false;
        // }
        return true;
    }
    thread: Thread;
    start(): void {
        log(`start`)
        if (this.isRuning) {
            updateFloat({ toast: `${this.title}已经执行` })
            return;
        }
        this.isRuning = true;
        updateFloat({ toast: `正在执行${this.title}任务`, currentTask: this.title })
        const latestActivity = runtime.info.latestActivity;
        if (['zd4.q', 'n27.a', 'u27.a', 'gqc.a', 'com.kuaishou.live.basic.dialog.LiveDialogContainerFragment$b'].includes(latestActivity)) {
            back();
            sleep(2000)
        }
        // 获取红包信息
        while (true) {
            sleep(1000)
            this.run()
        }
    }
    private run() {
        try {
            const res: any = httpGetSync2('getRedRoom', {
                uuid: getDeviceUuid()
            })
            updateFloat({ tip: '正在进入直播间' })
            new OpenLiveRoomAction(res.stream_id).run();
            updateFloat({ tip: '正在抢包' })
            this.joinRedPacket();
            updateFloat({ tip: '抢包结束' })
            sleep(3000)
        } catch (e) {
            updateFloat({ tip: e.message })
            sleep(3000 * 10)
        } finally {
            new ToShouYeAction(this.packageName).run()
            sleep(3000)
        }
    }
    private maxTime: number = 30 * 1000;
    private joinRedPacket() {
        let time = new Date().getTime()
        const node = selector().idEndsWith("live_red_packet_status_text").visibleToUser(true).findOne(this.maxTime)
        this.maxTime = ((new Date().getTime() - time) + this.maxTime) / 2;
        if (node) {
            $.tryClickButton(node)
            updateFloat({ currentResult: `成功打开红包弹框` })
            this.joinAndWaitRedPacket()
        } else {
            this.maxTime + 1000 * 10;
            updateFloat({ currentResult: `此房间暂无红包` })
            return;
        }
    }
    redPackets: RedPacket[] = [];
    getRedPacketViewPaper() {
        const viewPager = selector().classNameEndsWith('ViewPager').visibleToUser(true).findOne()
        const children = viewPager.children()
        return children;
    }
    private joinAndWaitRedPacket() {
        let children = this.getRedPacketViewPaper()
        updateFloat({ currentResult: `共有${children.length}个红包` })
        let joinCount: number = 0;
        for (let index = 0; index < children.length; index++) {
            console.log(`go ${index}`)
            try {
                const child = children.get(index);
                const bounds = child?.bounds()
                if (bounds) {
                    click(bounds.left + 50, (bounds.top + bounds.bottom) / 2);
                    sleep(3000)
                }
                children = this.getRedPacketViewPaper()
                let texts: string[] = [];
                const redPacket = new RedPacket();
                this.filterEachChildren(child, (node) => {
                    if(!node) return false;
                    const id = node?.id();
                    if (id && id.includes('action_view')) {
                        redPacket.setJoinButton(node)
                    }
                    let text = node.text()
                    if (text) texts.push(text)
                    return false;
                })
                redPacket.setText(texts.join(' '))
                if (redPacket.join()) {
                    joinCount += 1;
                    this.redPackets.push(redPacket)
                }
            } catch (e) {
                log(e.message)
            }
        }
        console.log(`join count ${joinCount}`)
        if (joinCount > 0) {
            updateFloat({ currentResult: `已参加${joinCount}个红包，等待开奖` })
            this.waitOpen();
        } else {
            updateFloat({ currentResult: `没有满足条件的红包` })
        }
    }
    private toRoom() {
        new ToLiveRoomAction(this.packageName).run()
    }
    private waitOpen() {
        new WaitRedOpenAction().run()
        this.toRoom();
        this.redPackets = [];
        if (this.isRuning) {
            // this.joinRedPacket()
        }
    }
    private filterEachChildren(node: UiObject, filter: (node: UiObject) => boolean) {
        const children = node.children();
        const list: UiObject[] = [];
        children.map(child => {
            if (filter(child)) {
                list.push(child)
            } else {
                list.push(...this.filterEachChildren(child, filter))
            }
        });
        return list;
    }
    packageName: string = $.PACKAGES["com.smile.gifmaker"];
    stop(): void {
        this.isRuning = false;
        if (this.thread && this.thread.isAlive()) {
            this.thread.interrupt()
        }
        updateFloat({ toast: `${this.title}任务执行结束`, currentTask: this.title })
        // new ToShouYeAction(this.packageName).run()
    }
}